package com.zc58s.springbootmqtt.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * @author : fujc-dev@qq.com
 * @created : 2022/9/21 11:56
 */

public class MqttPublishSample {

    public static final String topic = "WSN/CSN/sub/data/req";
    public static final String content = "{ \"sn\":1, \"wbtksn\":\"WTZ25100051000000M8T9000\", \"cloudsn\":\"cloud001\", \"type\":\"all\", \"codearr\":[ \"C_1001_VR_0000\", \"C_1001_VR_0001\" ] }";
    public static final String HOST = "tcp://111.198.38.198:7039";
    private static final String userName = "test01";
    private static final String passWord = "123456789";
    private static final String clientId = "kggs003";
    private static final int qos = 2;

    public static void main(String[] args) {

        MemoryPersistence persistence = new MemoryPersistence();
        try {
            MqttClient sampleClient = new MqttClient(HOST, clientId, persistence);
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(userName);
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            System.out.println("Connecting to broker: " + HOST);
            sampleClient.connect(options);
            System.out.println("Connected");
            System.out.println("Publishing message: " + options);
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            sampleClient.publish(topic, message);
            System.out.println("Message published");
            sampleClient.disconnect();
            System.out.println("Disconnected");
            System.exit(0);
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
}
